﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Xclna.Xna.Animation;

using SceneManager.Processors;

namespace SceneManager
{
    public class AnimatedModel : ComplexModel, ISkinnedObject
    {
        public ModelAnimator Animator { get; private set; }

        public AnimatedModel(Game game, string assetName, Vector3 position, Vector3 rotation, Vector3 scale) : base(game, game.Content.Load<Model>(assetName), position, rotation, scale)
        {
            Animator = new ModelAnimator(Game, Model);
            Animator.InitializeEffectParams();
            Animator.Visible = false;
        }

        public override void Draw(Camera camera, GameTime gameTime)
        {
            Matrix modelWorld = Matrix.CreateScale(Scale) * Matrix.CreateFromQuaternion(Rotation) * /*Matrix.CreateFromYawPitchRoll(Rotation.Y, Rotation.X, Rotation.Z) */ Matrix.CreateTranslation(Position);

            Matrix[] transforms = new Matrix[Model.Bones.Count];
            Animator.CopyAbsoluteTransformsTo(transforms);
            
            int i = 0;
            foreach (ModelMesh mesh in Model.Meshes)
            {
                Matrix meshWorld = transforms[mesh.ParentBone.Index] * modelWorld;

                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                {
                    meshPart.Effect = Effect;

                    meshPart.Effect.Parameters["World"].SetValue(meshWorld);
                    meshPart.Effect.Parameters["View"].SetValue(camera.View);
                    meshPart.Effect.Parameters["Projection"].SetValue(camera.Projection);
                    meshPart.Effect.Parameters["Texture"].SetValue(ModelMaterials[i].Texture);

                    if (meshPart.Effect.Parameters.Count(p => p.Name == "SpecularIntensity") == 1)
                        meshPart.Effect.Parameters["SpecularIntensity"].SetValue(ModelMaterials[i].SpecularIntensity);
                    if (meshPart.Effect.Parameters.Count(p => p.Name == "SpecularPower") == 1)
                        meshPart.Effect.Parameters["SpecularPower"].SetValue(ModelMaterials[i].SpecularPower);

                    i++;
                }
            }

            Animator.InitializeEffectParams();
            Animator.Draw(gameTime);
        }
    }
}
